import React, { useState, useEffect } from "react";
import { Page, Text } from "zmp-ui";
import { useNavigate } from "react-router-dom";
import { useI18n } from "../i18n";
import { siteApi } from "../api/login";
import { SiteInfo } from "../api/types";
import { MerchantTabType } from "../types/merchant";
import Navbar from "../components/navbar";

const Merchants: React.FunctionComponent = () => {
  const { t } = useI18n();
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState<MerchantTabType>("rent");
  const [sites, setSites] = useState<SiteInfo[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string>("");

  // 获取网点数据
  const fetchSites = async () => {
    setLoading(true);
    setError("");

    try {
      // 这里使用默认坐标，实际应用中应该获取用户当前位置
      const params = {
        lng: 105.9506553,
        lat: 20.99996219,
        distance: 5,
        total: 200,
      };

      const { data } = await siteApi.getAroundSites(params);
      console.log("网点API响应:", data);
      // HTTP客户端已经统一处理了响应格式，直接使用data
      setSites(data || []);
    } catch (err: any) {
      console.error("获取网点数据错误:", err);
      setError(err.message || t("merchants.fetchFailed"));
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    fetchSites();
  }, []);

  // 根据tab过滤数据
  const getFilteredSites = () => {
    switch (activeTab) {
      case "rent":
        // 可租借：有可借充电宝且营业中
        return sites.filter((site) => site.open && (site.depotBorrow || 0) > 0);
      case "return":
        // 可归还：有空置位置且营业中
        return sites.filter((site) => site.open && (site.depotEmpty || 0) > 0);
      case "all":
      default:
        return sites;
    }
  };

  const merchants = getFilteredSites();

  const getStatusColor = (site: SiteInfo): string => {
    if (site.open) {
      return "#4ECDC4";
    } else {
      return "#FF6B6B";
    }
  };

  const getStatusText = (site: SiteInfo): string => {
    return site.open ? t("merchants.open") : t("merchants.closed");
  };

  const tabs = [
    { key: "rent" as MerchantTabType, label: t("merchants.rent") },
    { key: "return" as MerchantTabType, label: t("merchants.return") },
    { key: "all" as MerchantTabType, label: t("merchants.all") },
  ];

  return (
    <Page
      className="page"
      style={{
        backgroundColor: "#F5F5F7",
        padding: 0,
        overflow: "auto",
        scrollbarWidth: "none",
        msOverflowStyle: "none",
      }}
    >
      <style>{`::-webkit-scrollbar { display: none; }`}</style>
      {/* 顶部导航栏 */}
      <div style={{ position: "sticky", top: 0, zIndex: 100 }}>
        <Navbar title={t("merchants.title")} />

        {/* Tab切换 */}
        <div
          style={{
            backgroundColor: "#EEEEF5",
            margin: "0 14px",
            borderRadius: "8px",
            padding: "4px",
            display: "flex",
          }}
        >
          {tabs.map((tab) => (
            <div
              key={tab.key}
              onClick={() => setActiveTab(tab.key)}
              style={{
                flex: 1,
                padding: "8px 12px",
                textAlign: "center",
                borderRadius: "6px",
                backgroundColor: activeTab === tab.key ? "#fff" : "transparent",
                cursor: "pointer",
                transition: "all 0.2s ease",
              }}
            >
              <Text
                style={{
                  fontSize: "14px",
                  fontWeight: activeTab === tab.key ? "bold" : "normal",
                  color: activeTab === tab.key ? "#39404D" : "#66666B",
                  margin: 0,
                }}
              >
                {tab.label}
              </Text>
            </div>
          ))}
        </div>
      </div>

      {/* 错误提示 */}
      {error && (
        <div
          style={{
            margin: "12px",
            padding: "12px 16px",
            background: "#ffebee",
            borderRadius: 8,
            color: "#c62828",
            fontSize: 14,
            textAlign: "center",
          }}
        >
          {error}
        </div>
      )}

      {/* 商户列表 */}
      <div style={{ padding: "12px" }}>
        {loading ? (
          /* 加载状态 */
          <div
            style={{
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              justifyContent: "center",
              padding: "60px 20px",
              color: "#666",
            }}
          >
            <div style={{ fontSize: "48px", marginBottom: "16px" }}>⏳</div>
            <div style={{ fontSize: "16px" }}>{t("merchants.loading")}</div>
          </div>
        ) : merchants.length > 0 ? (
          merchants.map((site) => (
            <div
              key={site.id}
              style={{
                backgroundColor: "#fff",
                borderRadius: "8px",
                marginBottom: "8px",
                padding: "12px",
                boxShadow: "0 1px 3px rgba(0,0,0,0.1)",
                cursor: "pointer",
              }}
              onClick={() => {
                // 跳转到商家详情页面
                navigate(`/merchant-detail?siteId=${site.id}&distance=${site.distance}`);
              }}
            >
              <div style={{ display: "flex", alignItems: "flex-start" }}>
                {/* 网点Logo */}
                <div
                  style={{
                    width: "80px",
                    height: "80px",
                    borderRadius: "5px",
                    backgroundColor: "#f0f0f0",
                    marginRight: "12px",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    fontSize: "24px",
                    color: "#999",
                  }}
                >
                  🏪
                </div>

                {/* 网点信息 */}
                <div style={{ flex: 1, minWidth: 0 }}>
                  {/* 网点名称 */}
                  <div
                    style={{
                      fontSize: "17px",
                      fontWeight: "bold",
                      color: "#39404D",
                      marginBottom: "4px",
                      lineHeight: "1.3",
                    }}
                  >
                    {site.name}
                  </div>

                  {/* 状态和营业时间 */}
                  <div
                    style={{
                      display: "flex",
                      alignItems: "center",
                      marginBottom: "6px",
                      flexWrap: "wrap",
                    }}
                  >
                    {/* 状态 */}
                    <div
                      style={{
                        fontSize: "11px",
                        color: getStatusColor(site),
                        marginRight: "10px",
                      }}
                    >
                      {getStatusText(site)}
                    </div>

                    {/* 营业时间 */}
                    <div
                      style={{
                        fontSize: "11px",
                        color: "#888888",
                        marginRight: "10px",
                      }}
                    >
                      {site.open_time}
                    </div>
                  </div>

                  {/* 地址 */}
                  <div
                    style={{
                      fontSize: "12px",
                      color: "#888888",
                      lineHeight: "1.4",
                      marginBottom: "4px",
                    }}
                  >
                    {site.address}
                  </div>

                  {/* 充电宝状态 */}
                  <div
                    style={{
                      fontSize: "11px",
                      color: "#666666",
                      display: "flex",
                      gap: "12px",
                    }}
                  >
                    <span>{t("merchants.availableForRent")}: {site.depotBorrow || 0}</span>
                    <span>{t("merchants.availableForReturn")}: {site.depotEmpty || 0}</span>
                  </div>
                </div>

                {/* 距离和导航 */}
                <div
                  style={{
                    display: "flex",
                    flexDirection: "column",
                    alignItems: "flex-end",
                    marginLeft: "12px",
                  }}
                >
                  {/* 距离 */}
                  <div
                    style={{
                      fontSize: "10px",
                      color: "#000",
                      marginBottom: "4px",
                    }}
                  >
                    {site.distanceCn}
                  </div>

                  {/* 导航图标 */}
                  <div
                    style={{
                      width: "12px",
                      height: "12px",
                      backgroundColor: "#007AFF",
                      borderRadius: "2px",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      fontSize: "8px",
                      color: "#fff",
                    }}
                  >
                    🗺️
                  </div>
                </div>
              </div>
            </div>
          ))
        ) : (
          /* 空状态 */
          <div
            style={{
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              justifyContent: "center",
              padding: "60px 20px",
              color: "#666",
            }}
          >
            <div style={{ fontSize: "48px", marginBottom: "16px" }}>☁️</div>
            <div style={{ fontSize: "16px", marginBottom: "8px" }}>
              {t("merchants.noData")}
            </div>
            <div style={{ fontSize: "14px", color: "#999" }}>{t("merchants.noMerchantData")}</div>
          </div>
        )}
      </div>
    </Page>
  );
};

export default Merchants;
